import React, { Component } from 'react'
import axios from '../utils/request'
import { Notify } from 'react-vant';

export default class Login extends Component {
    state = {
        username: '',
        password: ''
    }

    username(e) {
        this.setState({
            username: e.target.value,
        });
    }
    password(e) {
        this.setState({
            password: e.target.value,
        });
    }
    //登录
    tohome = () => {
        axios({
            url: '/api/login',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password
            }
        }).then(res => {
            console.log(res);
            if (res.data.code === 1) {
                window.localStorage.setItem('token', res.data.token)
                this.props.history.push('/main/home')
                //同步姓名和头像
                localStorage.setItem('username', res.data.data.username)
                localStorage.setItem('img', res.data.data.img)
                Notify.show({ type: 'success', message: res.data.msg });
            } else {
                Notify.show({ type: 'danger', message: res.data.msg });
            }
        })
    }

    //注册
    register = () => {
        axios({
            url: '/api/register',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password
            }
        }).then(res => {
            if (res.data.code === 2) {
                Notify.show({ type: 'warning', message: res.data.msg });
            } else {
                Notify.show({ type: 'success', message: res.data.msg })
            }
        })
    }

    render() {
        return (
            <div className="public1">
                <header>请先登录</header>
                <div className='login'>
                    <p>
                        {/* <label>用户名:</label> */}
                        <input type="text" placeholder="请输入用户名" onChange={(e) => { this.username(e) }} />
                    </p>
                    <p>
                        {/* <label>密   码:</label> */}
                        <input type="password" placeholder="请输入密码" onChange={(e) => { this.password(e) }} />
                    </p>
                    <button onClick={() => { this.tohome() }}>登录</button>
                    <button onClick={() => { this.register() }}>注册</button>
                </div>
            </div>
        )
    }
}
